package com.guoj.easyweb.interceptor;

import com.google.gson.Gson;
import com.guoj.easyweb.common.RequestHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @作者: guoj
 * @日期: 2019/6/22 16:39
 * @描述: http请求拦截器
 * 			-- 拦截所有请求，在请求前后做处理。
 */
@Component
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {
	private static final String START_TIME = "requestStartTime";

	/**
	 * 请求开始
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String url = request.getRequestURI().toString();
		Map parameterMap = request.getParameterMap();
//		log.info("request start. url:{}, params:{}", url, new Gson().toJson(parameterMap));
		long start = System.currentTimeMillis();
		request.setAttribute(START_TIME, start);
		return true;
	}

	/**
	 * 请求结束
	 * @param request
	 * @param response
	 * @param handler
	 * @param modelAndView
	 * @throws Exception
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//		String url = request.getRequestURI().toString();
//		long start = (Long) request.getAttribute(START_TIME);
//		long end = System.currentTimeMillis();
//		log.info("request finished. url:{}, cost:{}", url, end - start);

		// 清楚ThreadLocal绑定的内容
		removeThreadLocalInfo();
	}

	/**
	 * 请求完成
	 * @param request
	 * @param response
	 * @param handler
	 * @param ex
	 * @throws Exception
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		String url = request.getRequestURI().toString();
		long start = (Long) request.getAttribute(START_TIME);
		long end = System.currentTimeMillis();
//		log.info("request completed. url:{}, cost:{}", url, end - start);

		// 清楚ThreadLocal绑定的内容
		removeThreadLocalInfo();
	}

	public void removeThreadLocalInfo() {
		RequestHolder.remove();;
	}
}
